package com.yang.baseservice.aspect;


import com.yang.baseservice.annotation.Log;
import com.yang.baseservice.enums.LogNameEnum;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;

import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;


/**
 * 操作日志记录处理
 * 
 * @author ruoyi
 */
@Aspect
@Component
public class LogAspect
{
    private static final Logger log = LoggerFactory.getLogger("INFO_FILE");

    @Value("${app_log}")
    private static  Logger levelLog;
    /**
     * 进入方法时间戳
     */
    private Long startTime;
    /**
     * 方法结束时间戳(计时)
     */
    private Long endTime;

    public LogAspect() {
    }


    /**
     * 定义请求日志切入点，其切入点表达式有多种匹配方式,这里是指定路径
     */
    @Pointcut("@annotation(com.yang.baseservice.annotation.Log)")
    public void logPointcut() {
    }

    /**
     * 前置通知：
     * 1. 在执行目标方法之前执行，比如请求接口之前的登录验证;
     * 2. 在前置通知中设置请求日志信息，如开始时间，请求参数，注解内容等
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("logPointcut()")
    public void doBefore(JoinPoint joinPoint) throws Exception {

        Log controllerLog = getAnnotationLog(joinPoint);

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取请求头中的User-Agent
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //打印请求的内容
        startTime = System.currentTimeMillis();
        logLevelForApp(joinPoint, controllerLog);
        log.info("请求开始时间：{}", LocalDateTime.now());
        log.info("请求Url : {}", request.getRequestURL().toString());
        log.info("请求方式 : {}", request.getMethod());
        log.info("请求ip : {}", request.getRemoteAddr());
        log.info("请求方法 : ", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("请求参数 : {}", Arrays.toString(joinPoint.getArgs()));
        // 系统信息
        levelLog.info("浏览器：{}", userAgent.getBrowser().toString());
        levelLog.info("浏览器版本：{}", userAgent.getBrowserVersion());
        levelLog.info("操作系统: {}", userAgent.getOperatingSystem().toString());
        levelLog.info("请求开始时间：{}", LocalDateTime.now());
        levelLog.info("请求Url : {}", request.getRequestURL().toString());
        levelLog.info("请求方式 : {}", request.getMethod());
        levelLog.info("请求ip : {}", request.getRemoteAddr());
        levelLog.info("请求方法 : ",  joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName());

        levelLog.info("请求参数 : {}",argsArrayToString(joinPoint.getArgs()));
        // 系统信息
        levelLog.info("浏览器：{}", userAgent.getBrowser().toString());
        levelLog.info("浏览器版本：{}", userAgent.getBrowserVersion());
        levelLog.info("操作系统: {}", userAgent.getOperatingSystem().toString());
    }

    /**
     * 返回通知：
     * 1. 在目标方法正常结束之后执行
     * 1. 在返回通知中补充请求日志信息，如返回时间，方法耗时，返回值，并且保存日志信息
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "logPointcut()")
    public void doAfterReturning(Object ret) throws Throwable {
        endTime = System.currentTimeMillis();
        log.info("请求结束时间：{}", LocalDateTime.now());
        log.info("请求耗时：{}", (endTime - startTime));
        // 处理完请求，返回内容
        log.info("请求返回 : {}", ret);
        levelLog.info("请求结束时间：{}", LocalDateTime.now());
        levelLog.info("请求耗时：{}", (endTime - startTime));
        // 处理完请求，返回内容
        levelLog.info("请求返回 : {}", ret);
        levelLog=null;
    }

    /**
     * 异常通知：
     * 1. 在目标方法非正常结束，发生异常或者抛出异常时执行
     * 1. 在异常通知中设置异常信息，并将其保存
     *
     * @param throwable
     */
    @AfterThrowing(value = "logPointcut()", throwing = "throwable")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable throwable) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //获取请求头中的User-Agent
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //打印请求的内容
        startTime = System.currentTimeMillis();
        log.error("请求开始时间：{}", LocalDateTime.now());
        log.error("请求Url : {}", request.getRequestURL().toString());
        log.error("请求方式 : {}", request.getMethod());
        log.error("请求ip : {}", request.getRemoteAddr());
        log.error("请求方法 : ", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.error("请求参数 : {}", Arrays.toString(joinPoint.getArgs()));
        // 系统信息
        log.error("浏览器：{}", userAgent.getBrowser().toString());
        log.error("浏览器版本：{}", userAgent.getBrowserVersion());
        log.error("操作系统: {}", userAgent.getOperatingSystem().toString());
        // 保存异常日志记录
        log.error("发生异常时间：{}", LocalDateTime.now());
        log.error("抛出异常：{}", throwable.getMessage());


        levelLog.error("请求开始时间：{}", LocalDateTime.now());
        levelLog.error("请求Url : {}", request.getRequestURL().toString());
        levelLog.error("请求方式 : {}", request.getMethod());
        levelLog.error("请求ip : {}", request.getRemoteAddr());
        levelLog.error("请求方法 : ", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        levelLog.error("请求参数 : {}", Arrays.toString(joinPoint.getArgs()));
        // 系统信息
        levelLog.error("浏览器：{}", userAgent.getBrowser().toString());
        levelLog.error("浏览器版本：{}", userAgent.getBrowserVersion());
        levelLog.error("操作系统: {}", userAgent.getOperatingSystem().toString());
        // 保存异常日志记录
        levelLog.error("发生异常时间：{}", LocalDateTime.now());
        levelLog.error("抛出异常：{}", throwable.getMessage());
        levelLog=null;
    }
    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(Log.class);
        }
        System.out.println("null");
        return null;
    }

    private void logLevelForApp(JoinPoint joinPoint, Log log) throws Exception {
        if (log.value().equals("CQNX")) {
            levelLog = LoggerFactory.getLogger(LogNameEnum.BUSINESS_1.getLogName());
            System.out.println("cqnx");
        } else {
            levelLog = LoggerFactory.getLogger(LogNameEnum.BUSINESS_2.getLogName());
            System.out.println("aml");
        }
    }
    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray)
    {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0)
        {
            for (int i = 0; i < paramsArray.length; i++)
            {


                    try
                    {
                        Object jsonObj = JSON.toJSON(paramsArray[i]);
                        params += jsonObj.toString() + " ";
                    }
                    catch (Exception e)
                    {
                    }

            }
        }
        return params.trim();
    }
}
